import sqlparse


class SQLScriptExecutor:
    def __init__(self, db_instance):
        self.db = db_instance

    def execute_sql_file(self, file_path):
        """
        执行 SQL 文件中的多个脚本
        :param file_path: .sql 文件路径
        """
        # 读取 SQL 文件内容
        global cursor
        with open(file_path, 'r', encoding='utf-8') as f:
            sql_content = f.read()

        # 使用 sqlparse 分割 SQL 语句
        statements = sqlparse.split(sql_content)

        # 过滤空语句和注释
        valid_statements = [
            s.strip() for s in statements
            if s.strip() and not s.strip().startswith('--')
        ]

        # 获取数据库连接
        connection = self.db.engine.raw_connection()
        try:
            cursor = connection.cursor()
            # 逐条执行 SQL 语句
            for idx, sql in enumerate(valid_statements, 1):
                try:
                    cursor.execute(sql)
                    print(f"✅ 语句 {idx} 执行成功: {sql[:50]}...")
                except Exception as e:
                    print(f"❌ 语句 {idx} 执行失败: {sql[:50]}...")
                    print(f"错误信息: {str(e)}")
            # 提交事务
            connection.commit()
        except Exception as e:
            connection.rollback()
            raise RuntimeError(f"SQL 执行失败: {str(e)}")
        finally:
            cursor.close()
            connection.close()

        return len(valid_statements)


if __name__ == '__main__':
    pass
